package com.easytouch.core.task;

import android.content.Intent;

import com.easytouch.core.Configure;
import com.easytouch.core.utils.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * 提货码检查任务
 * Created by gulin on 2017/8/18.
 */

public class PickCodeCheckTask extends Task {

    public static final String INTENT_PICK_RESULT = "INTENT_PICK_RESULT";
    public static final String EXTRA_PICK_RESULT_CODE = "EXTRA_PICK_RESULT_CODE";
    public static final String EXTRA_PICK_RESULT_MESSAGE = "EXTRA_PICK_RESULT_MESSAGE";
    public static final String EXTRA_PICK_CODE = "EXTRA_PICK_CODE";

    private Log mLogger = new Log("PickCodeCheckTask.txt");

    public PickCodeCheckTask(final String pCode) {
        super(pCode);
    }

    @Override
    public void run() {
        mLogger.i("开始获取配置");
        String ip = Configure.getConfigData(Configure.CONFIG_PICK_IP);
        if (ip == null || ip.equals("")) {
            mLogger.e("提货码服务器IP为空");
            cleanup(-1, "local data error");
            return;
        }
        String portStr = Configure.getConfigData(Configure.CONFIG_PICK_PORT);
        if (portStr == null || portStr.equals("")) {
            mLogger.e("提货码服务器端口为空");
            cleanup(-1, "local data error");
            return;
        }
        int port;
        try {
            port = Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            mLogger.e("提货码服务器端口转换错误:" + e.getMessage());
            cleanup(-1, "local data error");
            return;
        }
        mLogger.i("开始连接");
        Socket socket = new Socket();
        InetSocketAddress socAddress = new InetSocketAddress(ip, port);
        InputStream in = null;
        OutputStream out = null;
        try {
            mLogger.i("Socket初始化");
            socket.connect(socAddress, 10000);
            in = socket.getInputStream();
            out = socket.getOutputStream();
            //发送数据:10 + 机器号 + 提货码 + 商品编号长度(2或者6)
            String sendStr = "10" + Configure.getMacNo() + getIdentifier() + "2";
            mLogger.i("提货码验证数据发送:" + sendStr);
            out.write(sendStr.getBytes());
            out.flush();
            //读取回应
            String lenStr = read(in, 3); //3位（长度）
            int len = Integer.parseInt(lenStr);
            String receiveMsg = read(in, len);
            mLogger.i("提货码验证数据接收:" + receiveMsg);
            // 2位（提货码长度）+10+10位提货码+1位状态码（ 1，表示正确；2，表示已使用；3，表示提货码不存在；4，表示提货码已过期；5表示提货码已锁定）+以-分隔的商品编码
            int codeLen = Integer.parseInt(receiveMsg.substring(0, 2));
            int pos = 2 + 2 + codeLen;
            int resultCode = Integer.parseInt(receiveMsg.substring(pos, pos + 1));
            String resultMessage = receiveMsg.substring(pos + 1);
            cleanup(resultCode, resultMessage);
        } catch (UnknownHostException e) {
            mLogger.e("提货码验证发生错误:" + e.getMessage());
            cleanup(-2, "net error");
        } catch (SocketTimeoutException e) {// 超时
            mLogger.e("提货码验证发生错误:" + e.getMessage());
            cleanup(-2, "net error");
        } catch (IOException e) {
            mLogger.e("提货码验证发生错误:" + e.getMessage());
            cleanup(-2, "net error");
        } catch (NumberFormatException e) {
            mLogger.e("提货码验证发生错误:" + e.getMessage());
            cleanup(-3, "data error");
        } catch (Exception e) {
            mLogger.e("提货码验证发生错误:" + e.getMessage());
            cleanup(-3, "data error");
        } finally {
            mLogger.i("关闭连接");
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
                if (socket != null)
                    socket.close();
            } catch (IOException ex) {
            }
        }
    }

    private void cleanup(final int pResultCode, final String pResultMessage) {
        mLogger.i("发送广播");
        TaskThreadPool.removeIdentifier(getIdentifier());
        mLogger.i("开始发送");
        //mLogger.i("cleanup");
        if (Configure.context != null) {
            Intent intent = new Intent(INTENT_PICK_RESULT);
            intent.putExtra(EXTRA_PICK_RESULT_CODE, pResultCode);
            intent.putExtra(EXTRA_PICK_RESULT_MESSAGE, pResultMessage);
            intent.putExtra(EXTRA_PICK_CODE, getIdentifier());
            Configure.context.sendBroadcast(intent);
            mLogger.i("发送完成");
            //mLogger.i("cleanup send broadcast");
        }
    }
}
